package com.bishe.app.modules.groupDaySaleCount.controller;

import com.alibaba.fastjson.JSON;
import com.bishe.app.core.api.CommonResult;
import com.bishe.app.core.api.CommonPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bishe.app.core.enums.IsDel;
import com.bishe.app.core.utils.Lock;
import com.bishe.app.modules.groupDaySaleCount.model.GroupDayCount;
import com.bishe.app.modules.groupDaySaleCount.model.GroupDaySaleReq;
import com.bishe.app.modules.groupuser.entity.GroupUser;
import com.bishe.app.modules.groupuser.enums.GroupUserPosition;
import com.bishe.app.modules.groupuser.service.GroupUserService;
import com.bishe.app.modules.userSaleIncome.service.UserSaleIncomeService;
import com.bishe.app.modules.userSaleIncome.service.impl.UserSaleIncomeServiceImpl;
import com.bishe.app.modules.usersaledetail.entity.UserSaleDetail;
import com.bishe.app.modules.usersaledetail.model.UserShopSaleItem;
import com.bishe.app.modules.usersaledetail.service.UserSaleDetailService;
import com.bishe.app.modules.usersaledetail.service.impl.UserSaleDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bishe.app.modules.groupDaySaleCount.service.GroupDaySaleCountService;
import com.bishe.app.modules.groupDaySaleCount.entity.GroupDaySaleCount;

import java.util.List;
import java.util.Objects;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * <p>
 * 店铺销售当天AB班统计 前端控制器
 * </p>
 *
 * @author
 * @since 2024-04-23
 */
@RestController
@RequestMapping("/groupDaySaleCount")
public class GroupDaySaleCountController {

    @Autowired
    public GroupDaySaleCountService groupDaySaleCountService;

    @Resource
    private UserSaleDetailService userSaleDetailService;

    @Resource
    private GroupUserService groupUserService;

    @Resource
    private UserSaleIncomeService userSaleIncomeService;

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    @Lock(lockPrefix = "/groupDayCount",key = "lock", lockSecond = 60)
    public CommonResult create(@RequestBody GroupDaySaleCount groupDaySaleCount) {
        boolean success = groupDaySaleCountService.save(groupDaySaleCount);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    @Lock(lockPrefix = "/groupDayCount",key = "lock", lockSecond = 60)
    @Transactional(rollbackFor = Throwable.class)
    public CommonResult doSaveDay(@RequestBody GroupDaySaleReq groupDaySaleReq) {
        // 先查询
        GroupDaySaleCount existCount = groupDaySaleCountService.lambdaQuery()
                .eq(GroupDaySaleCount::getGroupId, groupDaySaleReq.getGroupId())
                .eq(GroupDaySaleCount::getDate, groupDaySaleReq.getDate())
                .eq(GroupDaySaleCount::getIsDel, IsDel.N.getCode())
                .one();

        String[] dateArr = groupDaySaleReq.getDate().split("-");
        Integer year = Integer.parseInt(dateArr[0]);
        Integer mon = Integer.parseInt(dateArr[1]);
        Integer day = Integer.parseInt(dateArr[2]);


        if (existCount != null) {
            GroupDayCount groupDayCount = JSON.parseObject(existCount.getSaleItem(), GroupDayCount.class);
            if (groupDayCount != null) {
                groupDayCount.setSaleA(groupDaySaleReq.getSaleA());
                groupDayCount.setSaleB(groupDaySaleReq.getSaleB());
            }
            existCount.setSaleItem(JSON.toJSONString(groupDayCount));
            groupDaySaleCountService.updateById(existCount);
        } else {

            GroupDaySaleCount groupDaySaleCount = new GroupDaySaleCount();
            groupDaySaleCount.setGroupId(groupDaySaleReq.getGroupId());

            GroupDayCount groupDayCount = new GroupDayCount();
            groupDayCount.setSaleA(groupDaySaleReq.getSaleA());
            groupDayCount.setSaleB(groupDaySaleReq.getSaleB());
            groupDaySaleCount.setSaleItem(JSON.toJSONString(groupDayCount));

            groupDaySaleCount.setDate(groupDaySaleReq.getDate());

            groupDaySaleCount.setYear(year);
            groupDaySaleCount.setMon(mon);
            groupDaySaleCount.setDay(day);

            groupDaySaleCountService.save(groupDaySaleCount);
        }

        // get shop leader
        GroupUser one = groupUserService.lambdaQuery()
                .eq(GroupUser::getGroupId, groupDaySaleReq.getGroupId())
                .eq(GroupUser::getLeader, GroupUserPosition.LEADER.getGroupType())
                .eq(GroupUser::getIsDel, IsDel.N.getCode())
                .one();
        if (Objects.nonNull(one)) {
            // 更新店长的收入为 A + B
            UserSaleDetail leaderSaleDetail = userSaleDetailService.lambdaQuery()
                    .eq(UserSaleDetail::getUserId,one.getUserId())
                    .eq(UserSaleDetail::getDate,groupDaySaleReq.getDate())
                    .eq(UserSaleDetail::getIsDel,IsDel.N.getCode())
                    .one();
            if (leaderSaleDetail == null) {
                leaderSaleDetail = new UserSaleDetail();
                leaderSaleDetail.setUserId(one.getUserId());

                UserShopSaleItem userShopSaleItem = new UserShopSaleItem();
                userShopSaleItem.setSale(String.valueOf(UserSaleIncomeServiceImpl.calculate(groupDaySaleReq.getSaleA())
                        + UserSaleIncomeServiceImpl.calculate(groupDaySaleReq.getSaleB())));
                leaderSaleDetail.setSaleItem(JSON.toJSONString(userShopSaleItem));

                leaderSaleDetail.setDate(groupDaySaleReq.getDate());
                leaderSaleDetail.setYear(year);
                leaderSaleDetail.setMon(mon);
                leaderSaleDetail.setDay(day);

                userSaleDetailService.save(leaderSaleDetail);
            } else {
                UserShopSaleItem userShopSaleItem = new UserShopSaleItem();
                userShopSaleItem.setSale(String.valueOf(UserSaleIncomeServiceImpl.calculate(groupDaySaleReq.getSaleA())
                        + UserSaleIncomeServiceImpl.calculate(groupDaySaleReq.getSaleB())));
                leaderSaleDetail.setSaleItem(JSON.toJSONString(userShopSaleItem));
                userSaleDetailService.updateById(leaderSaleDetail);
            }

            userSaleIncomeService.calcIncome(groupDaySaleReq.getGroupId(), one.getUserId(), year, mon);
        }

        return CommonResult.success(null);
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    @Lock(lockPrefix = "/groupDayCount",key = "lock", lockSecond = 60)
    public CommonResult update(@PathVariable Long id, @RequestBody GroupDaySaleCount groupDaySaleCount) {
        groupDaySaleCount.setId(id);
        boolean success = groupDaySaleCountService.updateById(groupDaySaleCount);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    @Lock(lockPrefix = "/groupDayCount",key = "lock", lockSecond = 60)
    public CommonResult delete(@PathVariable Long id) {
        boolean success = groupDaySaleCountService.removeById(id);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @Lock(lockPrefix = "/groupDayCount",key = "lock", lockSecond = 60)
    public CommonResult deleteBatch(@RequestParam("ids") List<Long> ids) {
        boolean success = groupDaySaleCountService.removeByIds(ids);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }


    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<GroupDaySaleCount>> listAll() {
        List<GroupDaySaleCount> groupDaySaleCountList = groupDaySaleCountService.list();
        return CommonResult.success(groupDaySaleCountList);
    }

    @RequestMapping(value = "/pageList", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<GroupDaySaleCount>> page(@RequestBody CommonPage commonPage) {
        Page<GroupDaySaleCount> page = new Page(commonPage.getPageNum(), commonPage.getPageSize());
        return CommonResult.success(CommonPage.restPage(groupDaySaleCountService.page(page)));
    }
}



